//
//  SEGBillPaymentViewController.m
//  SEGUhomePropertyBaseService
//
//  Created by Clavis on 2019/3/5.
//  Copyright © 2019 刘山. All rights reserved.
//

// VC
#import "SEGBillPaymentViewController.h"
#import "SEGBillSelectRoomViewController.h"
#import "SEGPayLogYearListViewController.h"
// View
#import "SEGAddressView.h"
#import "SEGBillDeatilDisFeeView.h"
#import "SEGPayToolView.h"
#import "SEGBillPaymentHeaderView.h"
#import "SEGBillPaymentTableViewCell.h"
// Model
#import "SEGNewBillManager.h"
#import "SEGBillMonthModel.h"

@interface SEGBillPaymentViewController () <UITableViewDelegate, UITableViewDataSource, SEGBillSelectRoomViewDelegate>

@property (nonatomic, strong) SEGAddressView *addressView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) SEGBillDeatilDisFeeView* disFeeView; // 优惠信息视图
@property (nonatomic, strong) SEGPayToolView *payToolView;

@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) UILabel *totalAmountLabel;
@property (nonatomic, strong) UILabel *billDateLabel;

@property (nonatomic, strong) SEGNewBillManager *billManager;
@property (nonatomic, assign) BOOL isPayFuture; // 是否是预缴
@property (nonatomic, assign) __block BOOL isSupportPartPay; // 无纸化协议 是否支持每月单独缴费
@property (nonatomic, assign) __block BOOL isSupportItemAlonePay; // 是否支持每月下面按项单独缴费
@property (nonatomic, strong) NSArray<SEGBillMonthModel *> *dataSource;
@property (nonatomic, strong) NSMutableArray<SEGBillPaymentDiscInfoModel *> *payDiscountInfoArray; ///< 缴费时的优惠信息数组
@property (nonatomic, strong) SEGOwesDisFeeModel *matchPayDiscount; ///< 匹配的可用的优惠
@property (nonatomic, strong) SEGOwesDisFeeModel *originalPayDiscount; ///< 最初的可用的优惠
@property (nonatomic, strong) UIViewController *payListViewCtr;

@end

@implementation SEGBillPaymentViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 判断是否是预缴界面
    if (self.discountModel || self.selectFeeItemArray.count > 0) {
        self.isPayFuture = YES;
    }
    
    // 判断是否可以更改房屋信息 如果前一个页面有传值就不能更改
    //（从账单和预缴进来不能更改，缴费入口进来可以改）
    if (self.houseID && self.houseID.length > 0) {
        self.addressView.arrowImageView.hidden = YES;
        self.addressView.contentLabel.text = self.houseName;
        //配置无纸化账单
        [self checkNoPaper];
    } else {
        [self.addressView.titleBtn addTarget:self action:@selector(changeAddress:) forControlEvents:UIControlEventTouchUpInside];
        [self loadHouseList];
    }
    
    [self setupUI];
}

- (void)setupUI {
    if (self.isPayFuture) {
        self.title = self.title.length>0?self.title:@"预缴支付";
    } else {
        self.title = self.title.length>0?self.title:@"缴费";
    }
    self.view.backgroundColor = kColor_W;
    
    [self.view addSubview:self.addressView];
    [self.addressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.equalTo(self.view);
    }];
    
    [self.view addSubview:self.payToolView];
    [self.payToolView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.bottom.mas_equalTo(50);
        make.height.mas_equalTo(50);
    }];
    
    self.disFeeView = [[SEGBillDeatilDisFeeView alloc] init];
    [self.disFeeView setupUIWithIsHeader:NO];
    [self.view addSubview:self.disFeeView];
    [self.disFeeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(self.payToolView.mas_top);
    }];
    
    UIView *lineView = [[UIView alloc] init];
    lineView.backgroundColor = kColor_bg;
    [self.view addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.addressView.mas_bottom);
        make.left.right.offset(0);
        make.height.mas_equalTo(5);
    }];
    
    self.tableView = ({
        UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.backgroundColor = kColor_bg;
        tableView.tableFooterView = [[UIView alloc] init];
        tableView.estimatedRowHeight = 50.0f;
        tableView.rowHeight = UITableViewAutomaticDimension;
        [tableView registerClass:[SEGBillPaymentTableViewCell class] forCellReuseIdentifier:@"SEGBillPaymentTableViewCell"];
        [tableView registerClass:[SEGBillPaymentHeaderView class] forHeaderFooterViewReuseIdentifier:@"SEGBillPaymentHeaderView"];
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.view addSubview:tableView];
        tableView;
    });
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(lineView.mas_bottom);
        make.bottom.equalTo(self.disFeeView.mas_top);
    }];
    
    [self setupHeaderView];
    
    // 更新支付金额
    [self updatePayTooViewWithSpecifiedAmount:0];
    
    UIButton *payRecordButton = ({
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0, 0, 60, 40);
        [button setTitle:@"缴费记录" forState:UIControlStateNormal];
        [button setTitleColor:kColor_1 forState:UIControlStateNormal];
        button.titleLabel.font = kFont_13;
        [button addTarget:self action:@selector(payRecordButtonTap:) forControlEvents:UIControlEventTouchUpInside];
        button;
    });
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:payRecordButton];
    self.navigationItem.rightBarButtonItem = rightItem;
}

- (void)setupHeaderView {
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, LYScreenWidth(), 174)];
    headerView.backgroundColor = kColor_W;
    self.headerView = headerView;
    
    UILabel *titleLabel = ({
        UILabel *lable = [[UILabel alloc] init];
        [headerView addSubview:lable];
        lable.textColor = kColor_1;
        lable.font = [UIFont boldSystemFontOfSize:16];
        lable.text = self.isPayFuture ? @"预缴" : @"待缴";
        lable;
    });
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(15);
        make.left.mas_equalTo(15);
    }];
    
    if (self.isPayFuture) {
        UIView *lineView = [[UIView alloc] init];
        lineView.backgroundColor = kColor_L2;
        [headerView addSubview:lineView];
        [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(titleLabel.mas_right).offset(8);
            make.height.mas_equalTo(13);
            make.width.mas_equalTo(1);
            make.centerY.equalTo(titleLabel);
        }];
        
        UILabel *tipLabel = ({
            UILabel *lable = [[UILabel alloc] init];
            [headerView addSubview:lable];
            lable.textColor = kColor_C;
            lable.font = kFont_11;
            lable.text = @"如有待缴账单，一并展示";
            lable;
        });
        [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(lineView.mas_right).offset(8);
            make.centerY.equalTo(titleLabel);
        }];
    }
    
    UIView *backView = [[UIView alloc] init];
    backView.backgroundColor = [UIColor colorWithHexString:@"#FFB014"];
    backView.backgroundColor = kColor_T;
    backView.layer.cornerRadius = 5;
    backView.layer.masksToBounds = YES;
    [headerView addSubview:backView];
    [backView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(titleLabel.mas_bottom).offset(15);
        make.left.mas_equalTo(15);
        make.right.mas_equalTo(-15);
        make.bottom.mas_equalTo(-20);
    }];
    
    UILabel *tipLabel = ({
        UILabel *lable = [[UILabel alloc] init];
        [backView addSubview:lable];
        lable.textColor = kColor_W;
        lable.font = [UIFont boldSystemFontOfSize:13];
        lable.text = @"应缴总计";
        lable;
    });
    [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(14);
        make.top.mas_equalTo(20);
    }];
    
    self.totalAmountLabel = ({
        UILabel *lable = [[UILabel alloc] init];
        [backView addSubview:lable];
        lable.textColor = kColor_W;
        lable.font = [UIFont boldSystemFontOfSize:33];
        lable;
    });
    [self.totalAmountLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(tipLabel.mas_left);
        make.right.mas_equalTo(-14);
        make.top.equalTo(tipLabel.mas_bottom).offset(17);
    }];
    
    // 只有预缴才显示缴费日期范围
    if (_isPayFuture) {
        self.billDateLabel = ({
            UILabel *lable = [[UILabel alloc] init];
            [backView addSubview:lable];
            lable.textColor = kColor_W;
            lable.font = [UIFont boldSystemFontOfSize:13];
            lable;
        });
        [self.billDateLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(tipLabel.mas_left);
            make.top.equalTo(self.totalAmountLabel.mas_bottom).offset(18);
        }];
    }
    
    // 更新缴费总金额
    [self updateHeaderTotalAmount];
}

// 更新界面
- (void)updateUI {
    // 更新缴费总金额
    [self updateHeaderTotalAmount];
    // 更新账单时间
    [self updateBillDuration];
    // 更新优惠信息
    [self updateDiscountInfo];
    // 更新支付金额
    [self updatePayTooViewWithSpecifiedAmount:self.billManager.oweAmount - fabs(self.matchPayDiscount.disFee.doubleValue * MoneyRateChange) - fabs(self.matchPayDiscount.disLfree.doubleValue * MoneyRateChange)];
    // 默认全选
    [self.payToolView setRadioButtonSelected:YES];
}

/**
 切换小区的时候 重置当前页面数据
 */
- (void)resetUI {
    self.dataSource = [NSArray array];
    self.tableView.tableHeaderView = nil;
    [self.tableView reloadData];
    // 更新缴费总金额
    [self updateHeaderTotalAmount];
    // 更新优惠信息
    self.matchPayDiscount = nil;
    [self updateDiscountInfo];
    // 更新支付金额
    [self updatePayTooViewWithSpecifiedAmount:0.0];
    [self.payToolView setRadioButtonSelected:NO];
    [self updatePayToolConstraint];
}

// 更新缴费总金额
- (void)updateHeaderTotalAmount {
    NSMutableAttributedString *amountString = [[NSMutableAttributedString alloc] initWithString:@"￥" attributes:@{NSFontAttributeName: [UIFont boldSystemFontOfSize:22]}];
    [amountString appendAttributedString:[[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"%.2f", self.billManager.oweAmount] attributes:@{NSFontAttributeName: [UIFont boldSystemFontOfSize:33]}]];
    self.totalAmountLabel.attributedText = amountString;

}

// 更新优惠信息
- (void)updateDiscountInfo {
    NSString *disInfo = @"";
    if (self.matchPayDiscount.ruleId && self.matchPayDiscount.ruleId.length > 0) {
        disInfo = [NSString stringWithFormat:@"已参加%@活动，为您优惠了￥%.2f", self.matchPayDiscount.ruleName, fabs(self.matchPayDiscount.disFee.doubleValue *MoneyRateChange)];
    } else if (self.isPayFuture && self.discountModel.ruleId.length > 0 && self.dataSource.count > 0) {
        // 选择优惠活动进来的预缴,并且当前账单数据不为空,没有活动时要提示用户
        disInfo = @"预缴账单不满足活动条件，无法享受优惠";
    }
    [self.disFeeView updateUIWithText:disInfo];
}

// 更新账单时间
- (void)updateBillDuration {
    // 欠费不显示账单的时间范围
    if (!_isPayFuture) {
        self.headerView.frame = CGRectMake(0, 0, LYScreenWidth(), 174);
        return;
    }
    
    // 更新账单时间
    NSString *billDuration = @"";
    if (self.dataSource.count >= 2) {
        SEGBillMonthModel *firstMonth = self.dataSource.firstObject;
        SEGBillMonthModel *lastMonth = self.dataSource.lastObject;
        SEGBillMonthModel *maxMonth = nil;
        SEGBillMonthModel *minMonth = nil;
        if (firstMonth.billYear < lastMonth.billYear) {
            maxMonth = lastMonth;
            minMonth = firstMonth;
        } else if (firstMonth.billYear > lastMonth.billYear) {
            maxMonth = firstMonth;
            minMonth = lastMonth;
        } else if (firstMonth.billMonth < lastMonth.billMonth) {
            maxMonth = lastMonth;
            minMonth = firstMonth;
        } else {
            maxMonth = firstMonth;
            minMonth = lastMonth;
        }
        billDuration = [NSString stringWithFormat:@"%ld年%ld月-%ld年%ld月", (long)minMonth.billYear, (long)minMonth.billMonth, (long)maxMonth.billYear, (long)maxMonth.billMonth];
    }
    
    self.billDateLabel.text = billDuration;
    self.headerView.frame = CGRectMake(0, 0, LYScreenWidth(), billDuration.length > 0 ? 220 : 174);
}

/**
 更新下方支付View的价格

 @param payAmount 支付金额(单位:元)
 */
- (void)updatePayTooViewWithSpecifiedAmount:(CGFloat)payAmount {
    [self.payToolView setHidden:NO];
    [self.payToolView.titleBtn setEnabled:payAmount > 0 ? YES : NO];
    
    NSString* acctAmount = [NSString stringWithFormat:@"￥%.2f", payAmount];
    NSString* content = [NSString stringWithFormat:@"合计：%@", acctAmount];
    
    NSMutableAttributedString* attributedString = [[NSMutableAttributedString alloc] initWithString:content];
    [attributedString addAttributes:@{
                                      NSFontAttributeName : [UIFont systemFontOfSize:13],
                                      NSForegroundColorAttributeName : kColor_1
                                      }
                              range:NSMakeRange(0, content.length)];
    if (acctAmount.length > 0) {
        [attributedString addAttributes:@{
                                          NSFontAttributeName : [UIFont boldSystemFontOfSize:13],
                                          NSForegroundColorAttributeName : kColor_S1
                                          }
                                  range:[content rangeOfString:acctAmount]];
    }
    self.payToolView.contentLabel.attributedText = attributedString;
}

- (void)updateTablePlaceholder {
    NSString *tipString = self.isPayFuture ? @"暂无预缴账单" : @"暂无待缴账单";
    if (self.dataSource.count == 0) {
        self.tableView.tableHeaderView = nil;
        [[SEGUhomeMediator sharedInstance] seg_showCustomProgressImage:@{@"view":self.tableView, @"text":tipString, @"image":@"pic_default_nobills"}];
    } else {
        self.tableView.tableHeaderView = self.headerView;
        [[SEGUhomeMediator sharedInstance] seg_hideCustomProgressImage:@{@"view":self.tableView, @"text":tipString, @"image":@"pic_default_nobills"}];
    }
    
    [self updatePayToolConstraint];
}

- (void)updatePayToolConstraint {
    [self.payToolView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.bottom.mas_equalTo(self.dataSource.count > 0 ? -LYSafeAreaBottom() : 50);
        make.height.mas_equalTo(50);
    }];
}

// 更新当前总价和优惠信息
- (void)updateSelectAmountAndDiscount {
    // 更新当前总价
    NSInteger totalAmount = [self calculateCurrentSelectAmount];
    [self updatePayTooViewWithSpecifiedAmount: totalAmount * MoneyRateChange];
    
    // 如果最初账单包含优惠信息 就请求优惠匹配接口
    if (self.originalPayDiscount && self.originalPayDiscount.ruleId.length > 0) {
        // 更新优惠信息
        [self loadMatchDiscountInfo];
    }
}

// 更新全选按钮状态
- (void)updateAllSelectRadioStatus {
    BOOL isAllSelect = YES;
    for (SEGBillMonthModel *monthModel in self.dataSource) {
        if (!monthModel.isSelect) {
            isAllSelect = NO;
            break;
        }
    }
    [self.payToolView setRadioButtonSelected:isAllSelect];
}

#pragma mark - <UITableViewDelegate, UITableViewDataSource>
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataSource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    SEGBillMonthModel *monthModel = self.dataSource[section];
    return monthModel.billDetails.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SEGBillMonthModel *monthModel = self.dataSource[indexPath.section];
    SEGOwesMonthDetailModel *detailModel = monthModel.billDetails[indexPath.row];
    
    SEGBillPaymentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SEGBillPaymentTableViewCell" forIndexPath:indexPath];
    [cell updateUIWithModel:detailModel isHaveRadio:self.isSupportItemAlonePay && self.isSupportPartPay];
    [cell showDashLine:!(indexPath.row == monthModel.billDetails.count - 1)];
    WeakSelf;
    cell.changeRadioBlock = ^(BOOL isSelect) {
        [weakSelf billDetailRadioButtonTap:indexPath];
    };
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    SEGBillPaymentHeaderView *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"SEGBillPaymentHeaderView"];
    if (!header) {
        header = [[SEGBillPaymentHeaderView alloc] initWithReuseIdentifier:@"SEGBillPaymentHeaderView"];
    }
    SEGBillMonthModel *monthModel = self.dataSource[section];
    [header updateUIWithModel:monthModel isHaveRadio:self.isSupportPartPay];
    WeakSelf;
    header.changeRadioBlock = ^(BOOL isSelect) {
        [weakSelf monthRadioButtonTap:section];
    };
    header.backgroundColor = UIColor.orangeColor;
    return header;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 50;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}

#pragma mark - Data Handle
- (void)loadHouseList {
    // 不再请求房屋列表，直接使用用户数据返回的数据
    SEGProfileModel *userAccount = [SEGProfileManager sharedManager].profile;
    if (userAccount.houseList.count == 0) {
        self.addressView.contentLabel.text = @"没有可用的小区！";
        return;
    }
    
    self.houseID = userAccount.houseId;
    self.houseName = userAccount.houseName;
    self.custID = userAccount.custId;
    self.custType = userAccount.defaultCustType;
    self.addressView.contentLabel.text = self.houseName;
    
    //配置无纸化账单
    [self checkNoPaper];
}

/**
 *  查询无纸化账单配置
 */
- (void)checkNoPaper
{
    NSDictionary* params = @{
                             @"organId" : kAccountCommunityID,
                             @"houseId" : self.houseID
                             };
    WeakSelf;
    [SVProgressHUD show];
    
    [self.billManager checkNoPaper:params finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        [SVProgressHUD dismiss];
        
        NSDictionary* dict = result;
        //数据返回正常
        if (isSuccessed) {
            if (weakSelf.isPayFuture) {
                [weakSelf loadFutureBillList];
            } else {
                [weakSelf loadOweBillList];
            }
            
            weakSelf.isSupportPartPay = [dict[@"data"][@"isSupportPartPay"] integerValue] == 1;
            weakSelf.isSupportItemAlonePay = [dict[@"data"][@"appPartFeetypePay"] integerValue] == 1;
            if (weakSelf.isSupportPartPay) {
                [weakSelf.payToolView showRadioButton];
                weakSelf.payToolView.contentLabel.textAlignment = NSTextAlignmentRight;
                weakSelf.payToolView.contentLabel2.textAlignment = NSTextAlignmentRight;
            } else {
                [weakSelf.payToolView hideRadioButton];
                weakSelf.payToolView.contentLabel.textAlignment = NSTextAlignmentLeft;
                weakSelf.payToolView.contentLabel2.textAlignment = NSTextAlignmentLeft;
            }
            if ([dict[@"data"][@"isSet"] isEqualToString:@"1"] && [dict[@"data"][@"isAccept"] isEqualToString:@"0"]) { //本小区已配置协议，用户没有接受协议，2同意，1不同意，0还没有设置
                //跳转到协议界面
                NSMutableDictionary *webParams = [NSMutableDictionary dictionary];
                WeakSelf;
                id (^completed)(id, NSURL *) = ^id(id result, NSURL *url) {
                    [weakSelf agreeProtocol:[result integerValue]];
                    return nil;
                };
                [webParams setValue:@(SEGEnumWebType_Protocol) forKey:@"webType"];
                [webParams setValue:kPaperlessAgreement forKey:@"linkURL"];
                [webParams setValue:completed forKey:@"completed"];
                UIViewController *webVc = [[SEGUhomeMediator sharedInstance] seg_initWebViewLoadController:webParams];
                webVc.title = @"无纸化协议";
                webVc.hidesBottomBarWhenPushed = YES;
                [weakSelf.navigationController pushViewController:webVc animated:YES];
            }
        } else {
            [SEGAlertView showTmepMessageWithMessage:kNetworkErrorMessage];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf.navigationController popViewControllerAnimated:YES];
            });
        }
    }];
}


/**
 拉取预缴账单
 */
- (void)loadFutureBillList {
    NSMutableDictionary *params = [@{@"houseId":self.houseID,
                                     @"communityId":kAccountCommunityID,
                                     @"custId":self.custID,
                                     @"custType":self.custType,
                                     @"prepayitemflag":@"0"
                                     } mutableCopy];
    if (self.discountModel) {
        params[@"realCalcMethod"] = @"2";
        NSDictionary *discountDic = @{@"disInstId":self.discountModel.ruleId,
                                      @"feeItemTypeId":self.discountModel.feeItemTypeId,
                                      @"ruleConditionId":self.discountModel.ruleConditionId,
                                      @"ruleBeginCycleId":self.discountModel.ruleBeginCycleId,
                                      @"ruleEndCycleId":self.discountModel.ruleEndCycleId};
        params[@"disInfo"] = discountDic;
    } else if (self.selectFeeItemArray.count > 0) {
        params[@"realCalcMethod"] = @"1";
        NSMutableArray *feeDicArray = [NSMutableArray array];
        for (SEGBillFeeItemModel *feeItemModel in self.selectFeeItemArray) {
            // 账期结束时间要自己算
            NSDictionary *feeItemModelDic = @{@"instId":feeItemModel.instId,
                                              @"feeItemTypeId":feeItemModel.feeItemTypeId,
                                              @"startBillingCycle":feeItemModel.minUnpayCycle,
                                              @"endBillingCycle":[SEGNewBillManager calculateTimeBase:feeItemModel.minUnpayCycle intervalMonth:self.selectPayMonths - 1] ?: @""};
            [feeDicArray addObject:feeItemModelDic];
        }
        params[@"realTimeCalc"] = feeDicArray;
    }
    
    //SEGNewBillManager
    WeakSelf;
    [SVProgressHUD show];
    [self.billManager requestFutureBillListWithParamsDic:params finished:^(BOOL isSuccessed, NSString *codeType, NSString *errorMessage) {
        [SVProgressHUD dismiss];
        if (!isSuccessed) {
            [SEGAlertView showTmepMessageWithMessage:errorMessage];
            return;
        }
        
        weakSelf.dataSource = weakSelf.billManager.billMonthsArray;
        weakSelf.matchPayDiscount = weakSelf.billManager.payDiscount;
        weakSelf.originalPayDiscount = weakSelf.billManager.payDiscount;
        weakSelf.payDiscountInfoArray = weakSelf.billManager.payDiscountInfoArray;
        [weakSelf updateUI];
        [weakSelf.tableView reloadData];
        [weakSelf updateTablePlaceholder];
    }];
}


/**
 拉取欠费账单
 */
- (void)loadOweBillList {
    NSDictionary *params = @{@"houseId":self.houseID, @"communityId":kAccountCommunityID, @"custId":self.custID, @"custType":self.custType};
    WeakSelf;
    [SVProgressHUD show];
    [self.billManager requestPaymentBillListWithParamsDic:params finished:^(BOOL isSuccessed, NSString *codeType, NSString *errorMessage) {
        [SVProgressHUD dismiss];
        if (!isSuccessed) {
            [SEGAlertView showTmepMessageWithMessage:errorMessage];
            return;
        }
        
        weakSelf.dataSource = weakSelf.billManager.billMonthsArray;
        weakSelf.matchPayDiscount = weakSelf.billManager.payDiscount;
        weakSelf.originalPayDiscount = weakSelf.billManager.payDiscount;
        weakSelf.payDiscountInfoArray = weakSelf.billManager.payDiscountInfoArray;
        [weakSelf updateUI];
        [weakSelf.tableView reloadData];
        [weakSelf updateTablePlaceholder];
    }];
}


/**
 拉取匹配的优惠信息
 */
- (void)loadMatchDiscountInfo {
    NSMutableArray *disInfoArray = [NSMutableArray array];
    for (SEGBillPaymentDiscInfoModel *disInfoModel in self.payDiscountInfoArray) {
        NSMutableArray *disFeeArray = [NSMutableArray array];
        for (SEGOwesDisFeeModel *disFeeModel in disInfoModel.disFee) {
            NSDictionary *feeDic = @{@"ruleId" : disFeeModel.ruleId ?: @"",
                                     @"ruleName" : disFeeModel.ruleName ?: @"",
                                     @"disFee" : disFeeModel.disFee ?: @"",
                                     @"disLfree" : disFeeModel.disLfree ?: @"",
                                     @"billList" : disFeeModel.billList ?: @""
                                     };
            [disFeeArray addObject:feeDic];
        }
        
        NSMutableDictionary *disInfoDic = [NSMutableDictionary dictionary];
        disInfoDic[@"houseId"] = disInfoModel.houseId ?: @"";
        disInfoDic[@"disFee"] = disFeeArray;
        [disInfoArray addObject:disInfoDic];
    }
    
    NSString *selectBillID = [self calculateCurrnetSelectID];
    NSDictionary *params = @{@"acctItemStr": selectBillID,
                             @"disInfo" : disInfoArray
                             };
    
    WeakSelf;
    [self.billManager requestMatchDiscountWithParamsDic:params finished:^(BOOL isSuccessed, NSString *codeType, NSString *errorMessage) {
        weakSelf.matchPayDiscount = weakSelf.billManager.payDiscount;
        [weakSelf updateDiscountInfo];
        // 计算当前总价
        NSInteger totalAmount = [weakSelf calculateCurrentSelectAmount];
        totalAmount = totalAmount - labs(weakSelf.matchPayDiscount.disFee.integerValue) - labs(weakSelf.matchPayDiscount.disLfree.integerValue);
        [weakSelf updatePayTooViewWithSpecifiedAmount: totalAmount * MoneyRateChange];
    }];
}

/**
 计算当前选择的总价

 @return 总价(单位：分)
 */
- (NSInteger)calculateCurrentSelectAmount {
    NSInteger totalAmount = 0;
    for (SEGBillMonthModel *monthModel in self.dataSource) {
        for (SEGOwesMonthDetailModel *detailModel in monthModel.billDetails) {
            if (detailModel.isSelected) {
                totalAmount += detailModel.fee.integerValue + detailModel.lfree.integerValue;
            }
        }
    }
    return totalAmount;
}

// 计算当前选择的缴费项目的ID
- (NSString *)calculateCurrnetSelectID {
    NSMutableString *selectID = [NSMutableString string];
    for (SEGBillMonthModel *monthModel in self.dataSource) {
        for (SEGOwesMonthDetailModel *detailModel in monthModel.billDetails) {
            if (detailModel.isSelected) {
                [selectID appendString:detailModel.acctItemStr];
                [selectID appendString:@"-"];
            }
        }
    }
    return selectID;
}

#pragma mark - SEGBillSelectRoomViewDelegate - 切换小区
- (void)cell_didSelectedRoom:(SEGProfileHouselistModel *)data {
    self.houseID = data.houseId;
    self.houseName = data.fullHouseName;
    self.custID = self.custID;
    self.custType = self.custType;
    self.addressView.contentLabel.text = self.houseName;
    // 清空当前数据
    [self resetUI];
    [self checkNoPaper];
}

/**
 *  无纸化设置
 */
- (void)agreeProtocol:(NSUInteger)agreeStr {
    [SVProgressHUD show];
    NSDictionary* params = @{
                             @"organId" : kAccountCommunityID,
                             @"houseIds" : self.houseID,
                             @"noPaperFlag" : @(agreeStr)
                             };
    
    [self.billManager dealNoPaper:params finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        [SVProgressHUD dismiss];
        //数据返回正常
        if (!isSuccessed) {
            [SEGAlertView showTmepMessageWithMessage:errorMessage];
        }
    }];
}

#pragma mark - Action
- (void)changeAddress:(UIButton *)sender {
    SEGBillSelectRoomViewController* selectRoomVC = [[SEGBillSelectRoomViewController alloc] init];
    selectRoomVC.houseId = self.houseID;
    selectRoomVC.hidesBottomBarWhenPushed = YES;
    selectRoomVC.delegate = self;
    [self.navigationController pushViewController:selectRoomVC animated:YES];
}

// 点击月份的单选框
- (void)monthRadioButtonTap:(NSInteger)section {
    SEGBillMonthModel *monthModel = self.dataSource[section];
    monthModel.isSelect = !monthModel.isSelect;
    
    NSMutableArray<SEGOwesMonthDetailModel *> *tempDetails = [NSMutableArray array];
    for (SEGOwesMonthDetailModel *detailModel in monthModel.billDetails) {
        detailModel.isSelected = monthModel.isSelect;
        [tempDetails addObject:detailModel];
    }
    monthModel.billDetails = [tempDetails copy];
    
    NSMutableArray *tempMonths = [NSMutableArray arrayWithArray:self.dataSource];
    tempMonths[section] = monthModel;
    self.dataSource = [tempMonths copy];
    
    [self.tableView reloadSections:[[NSIndexSet alloc] initWithIndex:section] withRowAnimation:UITableViewRowAnimationAutomatic];
    
    // 更新全选按钮状态
    [self updateAllSelectRadioStatus];
    // 更新当前总价和优惠信息
    [self updateSelectAmountAndDiscount];
}

// 点击账单行的单选框
- (void)billDetailRadioButtonTap:(NSIndexPath *)indexpath {
    SEGBillMonthModel *monthModel = self.dataSource[indexpath.section];
    SEGOwesMonthDetailModel *detailModel = monthModel.billDetails[indexpath.row];
    detailModel.isSelected = !detailModel.isSelected;
    NSMutableArray<SEGOwesMonthDetailModel *> *tempDetails = [NSMutableArray arrayWithArray:monthModel.billDetails];
    tempDetails[indexpath.row] = detailModel;
    monthModel.billDetails = [tempDetails copy];
    
    BOOL isMonthAllSelect = YES;
    for (SEGOwesMonthDetailModel *detailModel in monthModel.billDetails) {
        if (!detailModel.isSelected) {
            isMonthAllSelect = NO;
            break;
        }
    }
    monthModel.isSelect = isMonthAllSelect;
    
    NSMutableArray *tempMonths = [NSMutableArray arrayWithArray:self.dataSource];
    tempMonths[indexpath.section] = monthModel;
    self.dataSource = [tempMonths copy];
    
    [self.tableView reloadSections:[[NSIndexSet alloc] initWithIndex:indexpath.section] withRowAnimation:UITableViewRowAnimationAutomatic];
    
    // 更新全选按钮状态
    [self updateAllSelectRadioStatus];
    // 更新当前总价和优惠信息
    [self updateSelectAmountAndDiscount];
}

// 点击全选按钮
- (void)payToolRadioClick:(BOOL)selectALL {
    NSMutableArray<SEGBillMonthModel *> *tempMonths = [NSMutableArray array];
    for (SEGBillMonthModel *months in self.dataSource) {
        months.isSelect = selectALL;
        
        NSMutableArray<SEGOwesMonthDetailModel *> *tempDetails = [NSMutableArray array];
        for (SEGOwesMonthDetailModel *detailModel in months.billDetails) {
            detailModel.isSelected = selectALL;
            [tempDetails addObject:detailModel];
        }
        months.billDetails = [tempDetails copy];
        [tempMonths addObject:months];
    }
    self.dataSource = [tempMonths copy];
    
    [self.tableView reloadData];

    // 更新当前总价和优惠信息
    [self updateSelectAmountAndDiscount];
}

- (void)payToolButtonClick:(UIButton *)sender {
    [SVProgressHUD show];
    // 获取支付列表
    WeakSelf;
    [self.billManager requestBillPaymentMethodListFinished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        [SVProgressHUD dismiss];
        if (!isSuccessed) {
            [SEGAlertView showTmepMessageWithMessage:kNetworkErrorMessage];
            return;
        }
        
        if ([codeType isEqualToString:@"-1"]  ) {
            [SEGAlertView showTmepMessageWithMessage:errorMessage];
            return;
        }
        
        [weakSelf.billManager requestPollByPayMethodResultWithParamsDic:@{@"requestId":[result valueForKey:@"data"]} Finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
            if (!isSuccessed || [codeType isEqualToString:@"-1"] ) {
                [SEGAlertView showTmepMessageWithMessage:errorMessage];
                return;
            }
            
            NSDictionary  *dic =[result valueForKey:@"data"];
            NSArray *mentodInfos = [dic valueForKey:@"mentodInfos"];
            
            
            if (![weakSelf.navigationController.childViewControllers containsObject:weakSelf.payListViewCtr]) { //解决多次连续按钮点击一直push
                
                NSString* acctItemIds = @"";
                NSInteger totalAmount = 0; //付款总金额(分)
                for (SEGBillMonthModel *monthModel in weakSelf.dataSource) {
                    for (SEGOwesMonthDetailModel *detailModel in monthModel.billDetails) {
                        if (detailModel.isSelected) {
                            acctItemIds = [acctItemIds stringByAppendingString:[NSString stringWithFormat:@"%@-", detailModel.acctItemStr]];
                            totalAmount += detailModel.fee.integerValue + detailModel.lfree.integerValue;
                        }
                    }
                }
                
                if (acctItemIds.length > 0) {
                    acctItemIds = [acctItemIds substringToIndex:acctItemIds.length - 1];
                }
                
//                NSDictionary* dataDic = @{
//                                        @"houseId" : weakSelf.houseID ?: @"",
//                                        @"acctItemIds" : acctItemIds,
//                                        @"custId" : weakSelf.custID ?: @"",
//                                        @"custType" : weakSelf.custType ?: @""
//                                        };
                /*
                 现在要传的优惠总金额要自己计算
                 优惠金额是负数，后台怎么传给我们，就怎么传给后台，不要取整
                 */
                NSInteger disAmount = weakSelf.matchPayDiscount.disFee.integerValue + weakSelf.matchPayDiscount.disLfree.integerValue;
                NSInteger payAmount = totalAmount - labs(disAmount); // 单位(分)
                NSDictionary* dataDic = @{
                                                @"houseId" : weakSelf.houseID ?: @"", //房号
                                                @"acctItemIds" : acctItemIds, //账单ID
                                                @"billAmount" : @(totalAmount), //账单总金额(分)
                                                @"payAmount" : @(payAmount), //付款总金额(分)
                                                @"disAmount" : @(disAmount), //优惠总金额(分)
                                                @"disRuleIdStr" : weakSelf.matchPayDiscount.ruleId ?: @"", //优惠规则ID
                                                @"custId" : weakSelf.custID ?: @"", //客户ID
                                                @"custType" : weakSelf.custType ?: @"" //客户类型
                                                };
   
                NSDictionary *param = @{@"dataDic":dataDic,
                                        @"orderIdOracctItemIds": acctItemIds,
                                        @"listData": mentodInfos,
                                        @"payTypeName": @(SEGPayTypeName_Bill)
                                        };
                
                UIViewController *payListVC = [[SEGUhomeMediator sharedInstance] seg_initPayListViewController:param];
                payListVC.hidesBottomBarWhenPushed = YES;
                weakSelf.payListViewCtr = payListVC;
                [weakSelf.navigationController pushViewController:payListVC animated:YES];
            }
        }];
    }];
}

- (void)payRecordButtonTap:(UIButton *)sender {
    SEGPayLogYearListViewController *recordVC = [[SEGPayLogYearListViewController alloc] init];
    recordVC.houseId = self.houseID;
    recordVC.custId = self.custID;
    recordVC.custType = self.custType;
    recordVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:recordVC animated:YES];
}

#pragma mark - Getter & Setter
- (SEGNewBillManager *)billManager {
    if (!_billManager) {
        _billManager = [[SEGNewBillManager alloc] init];
    }
    return _billManager;
}

- (SEGPayToolView*)payToolView {
    if (!_payToolView) {
        _payToolView = [[SEGPayToolView alloc] init];
        _payToolView.showType = @"2";
        [_payToolView.titleBtn addTarget:self action:@selector(payToolButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [_payToolView.titleBtn setTitle:@"支付" forState:UIControlStateNormal];
        [_payToolView.titleBtn setBackgroundImage:[UIImage imageWithColor:[UIColor lightGrayColor]] forState:UIControlStateDisabled];
        WeakSelf;
        _payToolView.radioSelectBlock = ^(BOOL isSelect) {
            if (isSelect) {
                [weakSelf payToolRadioClick:YES];
            } else {
                [weakSelf payToolRadioClick:NO];
            }
        };
    }
    return _payToolView;
}

- (SEGAddressView *)addressView {
    if (!_addressView) {
        _addressView = [[SEGAddressView alloc] init];
        _addressView.backgroundColor = kColor_W;
    }
    return _addressView;
}

@end
